from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from app.models.classroom import Classroom as ClassroomModel, ClassroomInDB
from app.schemas.classroom import Classroom as ClassroomSchema, ClassroomCreate, ClassroomUpdate
from app.schemas.response import APIResponse, PaginatedResponse
from app.config.database import get_db
from app.utils.responses import success_response, error_response, paginated_response
from app.utils.logger import logger
from datetime import datetime

router: APIRouter = APIRouter(prefix="/classrooms", tags=["classrooms"])

@router.post("/create", response_model=APIResponse[ClassroomSchema])
def create_classroom(classroom: ClassroomCreate, db: Session = Depends(get_db)):
    logger.info(f"Creating classroom with classroom_code: {classroom.classroom_code}")
    
    # 检查教室编码是否已存在
    db_classroom = db.query(ClassroomModel).filter(ClassroomModel.classroom_code == classroom.classroom_code).first()
    if db_classroom:
        logger.warning(f"Classroom already registered with classroom_code: {classroom.classroom_code}")
        return error_response(message="Classroom already registered", code=400)
    
    # 创建新教室
    db_classroom = ClassroomModel(
        classroom_code=classroom.classroom_code,
        classroom_name=classroom.classroom_name,
        building_no=classroom.building_no,
        floor_no=classroom.floor_no,
        room_no=classroom.room_no,
        capacity=classroom.capacity,
        room_type=classroom.room_type,
        status=classroom.status,
        create_time=datetime.utcnow(),
        update_time=datetime.utcnow()
    )
    
    db.add(db_classroom)
    db.commit()
    db.refresh(db_classroom)
    
    # 转换为Pydantic模型
    classroom_response = ClassroomInDB.model_validate(db_classroom)
    
    logger.info(f"Classroom created successfully with ID: {db_classroom.id}")
    return success_response(data=classroom_response, message="Classroom created successfully")

@router.get("/list", response_model=APIResponse[PaginatedResponse[ClassroomSchema]])
def read_classrooms(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    logger.info(f"Fetching classrooms with skip: {skip}, limit: {limit}")
    
    classrooms = db.query(ClassroomModel).offset(skip).limit(limit).all()
    # 转换为Pydantic模型
    classrooms_response = [ClassroomInDB.model_validate(classroom) for classroom in classrooms]
    total = db.query(ClassroomModel).count()
    
    logger.info(f"Found {len(classrooms)} classrooms")
    return paginated_response(
        items=classrooms_response,
        total=total,
        page=skip // limit + 1,
        size=limit
    )

@router.get("/{classroom_id}", response_model=APIResponse[ClassroomSchema])
def read_classroom(classroom_id: int, db: Session = Depends(get_db)):
    logger.info(f"Fetching classroom with ID: {classroom_id}")
    
    db_classroom = db.query(ClassroomModel).filter(ClassroomModel.id == classroom_id).first()
    if db_classroom is None:
        logger.warning(f"Classroom not found with ID: {classroom_id}")
        return error_response(message="Classroom not found", code=404)
    
    # 转换为Pydantic模型
    classroom_response = ClassroomInDB.model_validate(db_classroom)
    
    logger.info(f"Classroom found with ID: {classroom_id}")
    return success_response(data=classroom_response)

@router.put("/{classroom_id}", response_model=APIResponse[ClassroomSchema])
def update_classroom(classroom_id: int, classroom: ClassroomUpdate, db: Session = Depends(get_db)):
    logger.info(f"Updating classroom with ID: {classroom_id}")
    
    db_classroom = db.query(ClassroomModel).filter(ClassroomModel.id == classroom_id).first()
    if db_classroom is None:
        logger.warning(f"Classroom not found with ID: {classroom_id}")
        return error_response(message="Classroom not found", code=404)
    
    # 更新教室信息
    update_data = classroom.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_classroom, key, value)
    
    db_classroom.update_time = datetime.utcnow()
    db.commit()
    db.refresh(db_classroom)
    
    # 转换为Pydantic模型
    classroom_response = ClassroomInDB.model_validate(db_classroom)
    
    logger.info(f"Classroom updated successfully with ID: {classroom_id}")
    return success_response(data=classroom_response, message="Classroom updated successfully")

@router.delete("/{classroom_id}", response_model=APIResponse[None])
def delete_classroom(classroom_id: int, db: Session = Depends(get_db)):
    logger.info(f"Deleting classroom with ID: {classroom_id}")
    
    db_classroom = db.query(ClassroomModel).filter(ClassroomModel.id == classroom_id).first()
    if db_classroom is None:
        logger.warning(f"Classroom not found with ID: {classroom_id}")
        return error_response(message="Classroom not found", code=404)
    
    db.delete(db_classroom)
    db.commit()
    
    logger.info(f"Classroom deleted successfully with ID: {classroom_id}")
    return success_response(message="Classroom deleted successfully")
